package com.wx.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.wx.utils.KLKJID;

@Controller
@RequestMapping("/file")
public class FileController {
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	
	@Value("${file.dir}")
	String FILEPATH;
	@Value("${file.show}")
	String FILESHOW;
	
	@RequestMapping(value = "/uploadFile")
	@ResponseBody
	public Object uploadFile(@RequestBody MultipartFile file) {
		JSONObject resp = new JSONObject();
		try {
			File pp = new File(FILEPATH);
			if(pp.exists() == false) {
				pp.mkdirs();
			}
			String fileRealName = file.getOriginalFilename();
			byte[] bytes = null;
			try {
				bytes = file.getBytes();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        String type = fileRealName.substring(fileRealName.lastIndexOf(".")+1,fileRealName.length());
			String newName = KLKJID.uuid2();
			String rename = FILEPATH + newName + "." + type;
			Path path = Paths.get(rename);
			Files.write(path, bytes);
			resp.put("status", 1);
			resp.put("msg", "上传成功");
			resp.put("url", FILESHOW + "file/download/" + newName + "/inline/" + type);
			//return FILESHOW + "file/download/" + newName + "/inline/" + type;
		} catch (IOException e) {
			logger.error("文件上传异常：{}", e);
			resp.put("status", 0);
			resp.put("msg", "上传失败");
		}
		return resp.toJSONString();
	}
	
    @RequestMapping("/download/{id}/{type}/{ext}")
    public void downloadFile(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable("id")String id,
            @PathVariable("type")String type,
            @PathVariable("ext")String ext) throws IOException{
    	String hardPath = FILEPATH + id + "." + ext;
    	File file = new File(hardPath);
        if(file.exists()){
            this.downLoadFile(response, hardPath, type);
        }
    }
    
    protected void downLoadFile(HttpServletResponse response,String filePath, String type) throws IOException{
		File file=new File(filePath);
		String file_name = file.getName();
		response.setContentType("application/octet-stream;charset=GBK");
		response.setHeader("Content-disposition",""+type+";filename=\"" + new String(file_name.getBytes("gbk"),"iso8859-1") + "\"");
		FileInputStream fin = null;
		OutputStream fout = null;
		try{
			fin = new FileInputStream(file);
			fout = response.getOutputStream();
			byte[] b = new byte[1024];
			int i = 0;
			while((i = fin.read(b))>0){
				fout.write(b,0,i);
			}
			fout.flush();
		}
		catch(Exception e){
		}
		finally{
			if(fin!= null){
				fin.close();
				fin = null;
			}
			if(fout!= null){
				fout.close();
				fout = null;
			}
		}
	}
}
